package person.twj.securitysessionredis.core;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理类
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 返回的Map对象会被@ResponseBody注解转换为JSON数据返回
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map handleException(HttpServletRequest request, HttpServletResponse resp, Exception e){
        log.error("###出现异常！",e);
        System.out.println("###出现异常！");
        Map<String,Object> map=new HashMap<>();
        map.put("url",request.getRequestURL().toString());
        map.put("msg",e.getMessage());
        map.put("code",resp.getStatus());
        log.error("{}",e);


        try {
            if(e.getClass().isAssignableFrom(NoResourceFoundException.class)){
                resp.setStatus(404);
                request.getRequestDispatcher("/error/404.html").forward(request,resp);
                return null;
            }else if(e.getClass().isAssignableFrom(InsufficientAuthenticationException.class)){
                resp.setStatus(403);
                request.getRequestDispatcher("/error/403.html").forward(request,resp);
                return null;
            }

        } catch (Exception ex) {
            System.out.println("报错");
        }
        return map;
    }
}